package cn.spike.basic.interceptor;

import cn.spike.basic.jwt.JwtUtils;
import cn.spike.basic.jwt.LoginData;
import cn.spike.basic.jwt.RsaUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.concurrent.TimeUnit;

/**
 * @author:spike
 * @create:2023-02-10 16:02
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //因为我们配置类前置拦截器，将token放在了请求头数据包内
        //通过请求request获取请求头中的token
        String token = request.getHeader("token");
        if(token != null){  //如果token不等于null
            try {
                //解密获取登陆信息
                //先获取公钥  私钥加密 - 公钥解密
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //如果解密成功就说明有登录信息
                JwtUtils.getInfoFromToken(token,publicKey, LoginData.class);
                //放行
                return true;
            } catch (ExpiredJwtException e) {
                //如果报错说明登录过期 返回Json信息给后置拦截器
                //告诉浏览器，我要给你响应一个json数据，编码集为utf-8
                response.setContentType("application/json;charset/utf-8");
                //响应给前端 让前端做跳转
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
                return false;
            }
        }
        //告诉浏览器，我要给你响应一个json数据，编码集为utf-8
        response.setContentType("application/json;charset/utf-8");
        //响应给前端 让前端做跳转
        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
        return false;
    }
}
